package com.kingbook.core.scripting.nodes;


import com.kingbook.common.utils.StringUtils;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.jdom2.Element;

import java.util.*;

/**
 * @Author: Bucky
 * @Date: 2019/1/2
 * @Version 1.0
 */
public class TrimNode implements Node {

    protected String prefix = "";

    protected String suffix = "";

    protected List<String> prefixOverrides;

    protected List<String> suffixesOverrides;

    protected List<Node> nodeList = Lists.newArrayList();

    TrimNode() {
    }

    TrimNode(Element element) {
        prefix = element.getAttributeValue("prefix");
        suffix = element.getAttributeValue("suffix");
        prefixOverrides = parseOverrides(element.getAttributeValue("prefixOverrides"));
        suffixesOverrides = parseOverrides(element.getAttributeValue("suffixesOverrides"));
        resolve(nodeList, element);
    }

    @Override
    public String getSql(Map<String, ?> paramMap, Map<String, SegmentNode> segMap) {
        String sql = getSql(nodeList, paramMap, segMap).trim();
        StringBuilder sb = new StringBuilder(sql);
        if (CollectionUtils.isNotEmpty(prefixOverrides)) {
            for (String s : prefixOverrides)
                if (sql.startsWith(s)) {
                    sb.delete(0, s.length());
                    break;
                }
            if (sb.length()>0 && StringUtils.isNotEmpty(prefix))
                sb.insert(0, " " + prefix + " ");
        }
        if (CollectionUtils.isNotEmpty(suffixesOverrides)) {
            for (String s : suffixesOverrides)
                if (sql.endsWith(s)) {
                    sb.delete(sb.length() - s.length(), sb.length());
                    break;
                }
            if (sb.length()>0 && StringUtils.isNotEmpty(suffix))
                sb.append(" ").append(suffix).append(" ");
        }
        return sb.toString();
    }


    private static List<String> parseOverrides(String overrides) {
        if (StringUtils.isEmpty(overrides)) {
            return Collections.emptyList();
        } else {
            StringTokenizer parser = new StringTokenizer(overrides, "|", false);
            ArrayList<String> list = new ArrayList<String>(parser.countTokens());
            while (parser.hasMoreTokens()) {
                list.add(parser.nextToken().trim());
            }
            return list;
        }
    }


}
